<?php
namespace app\api\controller\pingan;

use think\Controller;

class Weixin extends Controller
{
    public function _initialize(){
            $data['openid']      = 'a4dd6b053e898c03141f1b34d602951a'; //PID
            $data['url']         = 'https://api.orangebank.com.cn/mct1/payorder';
            $data['openkey']     = 'a54f2971087199936913942780c8e867'; //KEY
            $this->config = $data;
    }
        
    public function index()
    {
        date_default_timezone_set('Asia/Shanghai');
        $outNo = 'CY' . date('YmdHis', time()) . rand(10, 99);
        $this->assign('timestamp', time());
        $this->assign('outNo', $outNo);
        return $this->fetch();
    }
    
    public function paylist()
    {
        $parameters = [
            'open_id'=>$this->config['openid'],
            'timestamp'=>time(),
            'pmt_type' => '3',
        ];
        $parameters['data'] = $this->payencrypt(json_encode($parameters), $this->config['openkey']);
		
        $parameters['sign'] = $this->signs($parameters, $this->config['openkey']);
        $result = $this->curl('https://mixpayuat4.orangebank.com.cn/mct1/paylist', $parameters);
        dump($result);
    }
    
    public function order()
    {
        $postData = input('post.'); 
       
        $parameters = [
            'open_id'  =>$this->config['openid'],
            'timestamp'=>time(),
        ];
		
        $parameters['data'] = $postData;

        $parameters['data'] = $this->payencrypt(json_encode($postData), $this->config['openkey']);
		
        $parameters['sign'] = $this->signs($parameters, $this->config['openkey']);

        $result = $this->curl($this->config['url'], $parameters);
        dump($result);
//        if(isset($result['data'])){
//            $result['data']=$this->decrypt($result['data'], $this->config['openkey']);
//            $result['data']=json_decode($result['data'], true);
//        }else{
//            return $result;
//        }
//        unset($result['sign']);
//
//        return  $result['data']['jsapi_pay_url'];
    }
    
    #@todo AES加解密
    #加密
    public function payencrypt($input, $key){
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = $this->pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = strtoupper(bin2hex($data));
        return $data;
    }

    public function pkcs5_pad ($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    
    #签名
    public function signs($array, $openkey) {
        $signature = array();
        foreach($array as $key=>$value){
            $signature[$key]=$key.'='.$value;
        }
        $signature['open_key']='open_key'.'='.$openkey;
        ksort($signature);
        #先sha1加密 在md5加密
        $sign_str = md5(sha1(implode('&', $signature)));
        return $sign_str;
    }


    #使用post的传输
    public function curl($url,$data){
        //启动一个CURL会话
        $ch = curl_init();
        // 设置curl允许执行的最长秒数
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        //忽略证书
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        // 获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_URL,$url);
        //发送一个常规的POST请求。
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_HEADER,0);//是否需要头部信息（否）
        // 执行操作
        $result = curl_exec($ch);
        if($result) {
            curl_close($ch);
            #将返回json转换为数组
            $arr_result=json_decode($result,true);
            if(!is_array($arr_result)) {
                $arr_result['errcode']=1;
                $arr_result['msg']='服务器繁忙，请稍候重试';
            }
        } else {
            $err_str=curl_error($ch);
            curl_close($ch);
            $arr_result['errcode']=1;
            $arr_result['msg']='服务器繁忙，请稍候重试';
        }
        #返回数据
        return $arr_result;

    }
    
     //解密
    public static function decrypt($sStr, $sKey) {
        $sStr=hex2bin($sStr);
        $decrypted= mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            $sKey,
            $sStr,
            MCRYPT_MODE_ECB
        );

        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }
}
